package com.csht.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.csht.model.City;
import com.csht.model.CshtUser;
import com.csht.model.Province;
import com.csht.model.School;
import com.csht.service.RegisterService;
import com.csht.util.GetMessage;
import com.csht.util.HttpRequest;
import com.csht.util.MD5;

import net.sf.json.JSONArray;

/**
 * 注册controller
 * @author chenhuiyan
 *
 */
@Controller
public class RegisterController {
	
	/**
	 * 获取省名称链接
	 */
	private String provinceUrl = "http://119.29.166.254:9090/api/provinces";
	
	/**
	 * 通过省id查找城市
	 */
	private String cityUrl = "http://119.29.166.254:9090/api/province/getCitiesByProvinceId";
	
	/**
	 * 通过城市名获取学校
	 */
	private String schoolUrl = "http://119.29.166.254:9090/api/university/getUniversityByCityName";
	
	@Autowired
	private RegisterService registerService;
	
	/**
	 * 注册页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	public String register(ModelMap model) throws Exception {
		String result = HttpRequest.sendPost(provinceUrl, "");
		//json字符串转化list
		JSONArray json = JSONArray.fromObject(result);//result是json字符串
		@SuppressWarnings("unchecked")
		List<Province> provinceList= (List<Province>)JSONArray.toList(json, Province.class);
		model.addAttribute("provinceList", provinceList);
		CshtUser cshtUser = new CshtUser();
		model.addAttribute("cshtUser", cshtUser);
		System.out.println(provinceList);
		return "/register/register";
	}
	
	/**
	 * ajax，根据省id获取城市
	 * @param provinceId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getCity")
	public Map<String, List<City>> getCity(@RequestParam(name = "provinceId") Integer provinceId) throws Exception{
		Map<String, List<City>> city = new HashMap<String, List<City>>();
		String result = HttpRequest.sendPost(cityUrl, "id=" + provinceId);
		//json字符串转化list
		JSONArray json = JSONArray.fromObject(result);//result是json字符串
		@SuppressWarnings("unchecked")
		List<City> cityList= (List<City>)JSONArray.toList(json, City.class);
		city.put("cityList", cityList);
		System.out.println(cityList);
		return city;
	}
	
	/**
	 * ajax，根据城市名获取学校
	 * @param cityName
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getSchool")
	public Map<String, List<School>> getSchool(@RequestParam(name = "cityName") String cityName) throws Exception{
		Map<String, List<School>> school = new HashMap<String, List<School>>();
		String result = HttpRequest.sendPost(schoolUrl, "name=" + cityName);
		//json字符串转化list
		JSONArray json = JSONArray.fromObject(result);//result是json字符串
		@SuppressWarnings("unchecked")
		List<School> schoolList= (List<School>)JSONArray.toList(json, School.class);
		school.put("schoolList", schoolList);
		System.out.println(schoolList);
		return school;
	}
	/**
	 * 验证用户是否存在
	 * @param username
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUsername")
	public Map<String, Object> checkUsername(@RequestParam(name = "username") String username) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("res", false);
		CshtUser cshtUser = registerService.getUserByUsername(username);
		if(cshtUser == null) {
			messages.put("res", true);
		}
		return messages;
	}
	
	/**
	 * 检验用户手机号码是否已注册
	 * @param userTel
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUserTel")
	public Map<String, Object> checkUserTel(@RequestParam(name = "userTel") String userTel) throws Exception{
		CshtUser cshtUser = registerService.findUserByTel(userTel);
		Map<String, Object> messages = new HashMap<String, Object>();
		if(cshtUser != null) {
			messages.put("bool", false);
		}else {
			messages.put("bool", true);
		}
		return messages;
	}
	
	/**
	 * 发短信获取手机验证码
	 * @param tel
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getCode")
	public Map<String, Object> getCode(@RequestParam(name = "telval") String tel, 
			@RequestParam(name = "getCodeType") String getCodeType) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		String result = GetMessage.getResult(tel, getCodeType); //调用发短信方法发送信息并返回结果
		if(result.length() != 6) {
			messages.put("bool", false);
		}else {
			messages.put("bool", true);
		}
		messages.put("telCode", result);
		System.out.println("发至手机号：" + tel + "   验证码为：" + result);
		return messages;
	}
	
	/**
	 * 注册
	 * @param multipartFile
	 * @param cshtUser
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/userReg")
	public String userReg(@RequestParam(name = "userhead") MultipartFile multipartFile, CshtUser cshtUser, 
			HttpSession session, RedirectAttributes redirectAttributes) throws Exception{
		if(multipartFile.getOriginalFilename() == null || multipartFile.getOriginalFilename() =="") { //用户不上传头像
			cshtUser.setUserHeadPath("avater.jpg");
		}else {
			String riginalFilename = multipartFile.getOriginalFilename(); //获取原文件名
			String path = "D:/Tomcat/csht_file/user_header/"; //上传文件路径
			String fileSuffixName = riginalFilename.substring(riginalFilename.lastIndexOf(".") + 1); //截取后缀名
			String fileName = System.currentTimeMillis() + "." + fileSuffixName; //文件名
			File file = new File(path, fileName); //创建文件
			multipartFile.transferTo(file); //保存文件
			cshtUser.setUserHeadPath(fileName);
		}
		cshtUser.setUserPassword(MD5.getMD5Code(cshtUser.getUserPassword()));//密码MD5加密
		registerService.userRegister(cshtUser);
		redirectAttributes.addFlashAttribute("message", "成功");
		return "redirect:/register";
	}

}
